package bTree.LeetCode;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 有序链表转换二叉搜索树 {
    public TreeNode sortedListToBST(ListNode head) {
        List<Integer>list=new ArrayList<>();
        ListNode p=head;
        while (p!=null){
            list.add(p.val);
            p=p.next;
        }
        int[] array = list.stream().mapToInt(i -> i).toArray();
        return makeTreeNode(array);
    }

    private TreeNode makeTreeNode(int[] array) {
        if (array.length==0){
            return null;
        }
        int mid=array.length/2;
        TreeNode node=new TreeNode(array[mid]);
        node.left=makeTreeNode(Arrays.copyOfRange(array, 0, mid));
        node.right=makeTreeNode(Arrays.copyOfRange(array, mid+1, array.length));
        return node;
    }
}